<?php
require "init.php";

/** @var PDO $pdo 数据对象 */

//事务
try {
    //设定报错的方式，如果发生错误则抛出一个异常
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    //开始一个事务
    $pdo->beginTransaction();

    $pdo->exec("INSERT INTO `demo`.`record` (`id`, `name`, `date`, `description`) VALUES (NULL, 'zhangsan', '23423424', 'transaction-flag')");

    $pdo->exec("INSERT INTO `demo`.`record2` (`id`, `name`, `date`, `description`) VALUES (NULL, '3213eef', '23423424', 'transaction-flag 2')");

    //提交事务
    $pdo->commit();
} 
catch (Exception $exec) {
    /**
     * 回滚事务
     * 如果脚本意外终止也会自动回滚
     */
    $pdo->rollBack();
    header('Content-Type: text/plain');
    print_r($exec);
}

//回滚后，已经插入的数据会消失
$result=$pdo->query("SELECT * FROM `demo`.`record` WHERE `description` LIKE 'transaction-flag'");
$data=$result->fetchAll(PDO::FETCH_ASSOC);
echo count($data);
